package com.wlf.util;

import com.wlf.constant.Fonts;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import org.plutext.jaxb.xslfo.Root;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author lingfeng.wei
 * @date 2022/1/12 10:30
 */
@Component
public class FopUtils {

    @Value("${env.file.temp.path}")
    private String path;

    /**
     * 返回临时生成的pdf
     * @param root
     * @return
     * @throws Exception
     */
    public   File createTempPdf(Root root,JAXBContext content) throws Exception{

        StringWriter sw=null;
        File file = File.createTempFile("tempPdf",".pdf");
        sw=new StringWriter();
        Marshaller mar=content.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        mar.setProperty(Marshaller.JAXB_ENCODING,System.getProperty("file.encoding"));
        mar.marshal(root, sw);
        String str=sw.toString();
        str=str.replace("\\", "/");
        str=str.replace("&amp;#8203;", "&#8203;");
        str=str.replace("&amp;#160;", "&#160;");
        StringReader read = new StringReader(str);

        FopFactory factory = FopFactory.newInstance(new File(this.getFopUrl()));

        OutputStream out = null;

        out = new FileOutputStream(file);
        out = new BufferedOutputStream(out);
        Fop fop = factory.newFop(MimeConstants.MIME_PDF, out);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        Source source = new StreamSource(read);
        Result res = new SAXResult(fop.getDefaultHandler());
        transformer.transform(source, res);
        out.close();

        return  file;
    }

    /**
     * 获取字体跟文件
     * @return
     */
    private String getFopUrl(){
        try{
            //项目每次次启动后访问更新下载字体
            if(!Fonts.IS_COPY_FOP_FILE){
                File dir =new File(path);
                //创建字体存放目录
                if(!dir.exists()){
                    //创建目录
                    dir.mkdirs();
                }
                //复制字体到该目录下
                for (String fileName : Fonts.FOP_FONTS) {
                    File file = new File(path + File.separator+ fileName);
                    if (file.exists()){
                        file.delete();
                    }
                    file.createNewFile(); //创建文件
                    OutputStream out = new FileOutputStream(file);
                    Resource resource = new ClassPathResource(Fonts.FOP+File.separator+fileName);
                    InputStream is = resource.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    byte[] buf = new byte[2048];
                    int len = 0;
                    while ((len = bis.read(buf)) != -1)
                        out.write(buf, 0, len);
                    bis.close();
                    out.flush();
                    is.close();
                    if (out != null) {
                        out.close();
                    }
                }
            }
            //检查FOP文件
            File file = new File(path + File.separator +Fonts.FOP_URL);
            if(!Fonts.IS_COPY_FOP_FILE){
                if(file.exists()){
                    file.delete();
                }
                file.createNewFile(); //创建文件
                OutputStream out = new FileOutputStream(file);
                Resource resource = new ClassPathResource(Fonts.FOP+File.separator+Fonts.FOP_URL);
                InputStream is = resource.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                byte[] buf = new byte[2048];
                int len = 0;
                while ((len = bis.read(buf)) != -1)
                    out.write(buf, 0, len);
                bis.close();
                out.flush();
                is.close();
                if (out != null) {
                    out.close();
                }
                Fonts.IS_COPY_FOP_FILE=Boolean.TRUE;
            }
            return file.getPath();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
